<?php

class IndexController extends Zend_Controller_Action
{
    //--------------------------------------------------------------------------
    public function init()
    {
    }
    //--------------------------------------------------------------------------
    public function indexAction()
    {   $this->view;
    }
    //--------------------------------------------------------------------------
    public function loginAction()
    {
        $request = $this->getRequest();
        
        if ( ! Zend_Auth::getInstance()->hasIdentity() )
        {   if ($request->getParam('p1')!="")
            {   $nombre = $request->getParam('p1');
                $clave = $request->getParam('p2');
                if ($this->_process($nombre, $clave))
                {   //Exito
                    $this->_redirect('/index');
                }
            }
        } 
        else 
        {   $this->borrarSesion();
        }
        
        $this->_redirect('https://ZendPhp.local');
    }
    //--------------------------------------------------------------------------
    public function logoutAction()
    {   $this->borrarSesion();
        $this->_redirect('/index');
    }
    //--------------------------------------------------------------------------
    protected function borrarSesion()
    {   Zend_Auth::getInstance()->clearIdentity();
        session_destroy();
        $parametros_cookies = session_get_cookie_params();
        setcookie(session_name(),0,1,$parametros_cookies["path"]);
    }
    //--------------------------------------------------------------------------
    public function unaaccionAction()
    {
        // action body
    }
    //--------------------------------------------------------------------------
    protected function _getAuthAdapter()
    {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
        $authAdapter->setTableName('usuarios')
            ->setIdentityColumn('nombre')
            ->setCredentialColumn('clave');
        return $authAdapter;
    }
    //--------------------------------------------------------------------------
    protected function _process($nombre,$clave)
    {
        $adapter = $this->_getAuthAdapter();
        $adapter->setIdentity($nombre);
        $adapter->setCredential($clave);
        
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if ($result->isValid())
        {
            $user = $adapter->getResultRowObject();
            $auth->getStorage()->write($user);
            return true;
        }
        return false;
    }
    //--------------------------------------------------------------------------

}







